package com.whosly.demo.jmh.rocksdb;

import lombok.Getter;
import org.apache.commons.io.FileUtils;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author fengyang
 * @date 2023/8/8 下午8:35
 * @see <a href="yueny09@163.com">mailTo: yueny09@163.com</a>
 */
public class RocksDBWrapper
{
    private File dataDir;
    private RocksDB db;

    @Getter
    private String indexInstanceId;

    public RocksDBWrapper(String dbDir, RocksDB rocksdb)
    {
        this.dataDir = new File(dbDir);
        this.db = rocksdb;
        this.indexInstanceId = UUID.randomUUID().toString();
    }

    public File getDataDir() {
        return dataDir;
    }

    public void cleanLogDir() throws IOException
    {
        if (dataDir.exists()) {
            FileUtils.deleteDirectory(dataDir);
        }
    }

//    public void create() throws RocksDBException
//    {
//        synchronized (indexInstanceId.intern()) {
//            this.db = RocksDBManager.getInstance().create(this.dataDir);
//        }
//    }
//
//    public void open() {
//        assert (dataDir != null);
//        if (db == null) {
//            synchronized (indexInstanceId.intern()) {
//                if (db == null) {
//                    try {
//                        this.db = RocksDBManager.getInstance().open(dataDir);
//                    } catch (RocksDBException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//    }
//
//    public boolean isOpen() {
//        return db != null;
//    }

    public void close() {
        synchronized (indexInstanceId.intern()) {
            if (db != null) {
                db.close();
                db = null;
            }
        }
    }

    /**
     * Get the rowId of the pair.
     *
     * @param key
     * @return rowId of the key, -1 indicates not found
     */
    public byte[] get(byte[] key) throws RocksDBException {
        return db.get(key);
    }

    /**
     * Put, without checking if key already exists.
     */
    public void put(byte[] key, byte[] rowId) throws RocksDBException {
        if(db == null) {
            return;
        }

        synchronized (indexInstanceId.intern()) {
            if(db == null) {
                return;
            }

            db.put(key, rowId);
        }
    }

    /**
     * Put, without checking if key already exists.
     */
    public void putUnsafe(byte[] key, byte[] rowId) throws RocksDBException {
        db.put(key, rowId);
    }

    /**
     * Delete the row. If the row exists, remove it. If the row does not exist,
     * do nothing.
     *
     * @param key
     */
    public void delete(byte[] key) throws RocksDBException {
        db.delete(key);
    }
}
